package cn.kgc.javaweb.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author: mosin
 * @version: v1.0  2022/8/26
 *使用连接池 封装数据库操作的工具类  获取连接 释放资源
 */
public class DruidUtil {

    private  static  DataSource dataSource;
    private DruidUtil(){}

    static {
        //创建properties 对象解析 properties文件
        Properties properties = new Properties();
        //获取类加载器  读取根路径下的资源文件
        ClassLoader classLoader = DruidUtil.class.getClassLoader();
        InputStream resourceAsStream = classLoader.getResourceAsStream("druid.properties");
        try {
            properties.load(resourceAsStream);
            // 实例化一个数据库连接池
           dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取数据库连接池的方法
    public static DataSource getDataSource(){
        return dataSource;
    }

    //获取数据库的连接
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    //释放资源
    public static  void  closeAll(Connection connection, Statement statement, ResultSet resultSet){

        if(resultSet!=null){

            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }

        if(statement!=null){

            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }

        if(connection!=null){

            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }

    }

}
